package com.tuozixuan.jmh.me;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Measurement(iterations = 3, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Warmup(iterations = 3, time = 100, timeUnit = TimeUnit.MILLISECONDS)
public class ListSizeInLoop {
	
	private static List<String> list = new ArrayList<String>();
	
	static {
		for (int i = 0; i < 100000; i++) {
			list.add("item" + i);
		}
	}
	

	@Benchmark
	public void getSizeBySizeMethod(Blackhole bh) {
		
		int sum = 0;
		for (int i = 0; i < list.size(); i++) {
			sum += i;
		}
		bh.consume(sum);
	}
	
	@Benchmark
	public void getSizeByLocalVar (Blackhole bh) {
		int sum = 0;
		for (int i = 0, size = list.size(); i < size; i++) {
			sum += i;
		}
		bh.consume(sum);
	}
	
	public static void main(String[] args) throws RunnerException {
		Options opt = new OptionsBuilder().include(ListSizeInLoop.class.getSimpleName()).forks(1).build();
		new Runner(opt).run();
	}
}
